package com.fzebu.fastboot.db.builder;

import com.fzebu.fastboot.db.intl.AbstractSQLBuilder;
import org.apache.commons.lang.StringUtils;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Map;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * @author Jack
 * @version 1.0.0
 * @create 2020/2/16 21:36
 */
public class UpdateBuilder extends AbstractSQLBuilder {

    private String where;

    private Object[] conditionParams;

    public UpdateBuilder table(String table) {
        this.setTableName(table);
        return this;
    }

    public UpdateBuilder param(String key, Object val) {
        this.setParam(key, val);
        return this;
    }

    public UpdateBuilder where(String where, Object ... conditionParams) {
        this.where = where;
        this.conditionParams = conditionParams;
        return this;
    }

    public UpdateBuilder conditionParams(Object ... conditionParams) {
        this.conditionParams = conditionParams;
        return this;
    }

    @Override
    protected String buildSql(String table, Map<String, Object> paramMap) {
        StringBuilder sql = new StringBuilder()
                .append("UPDATE ")
                .append(table)
                .append(" SET ");
        AtomicBoolean first = new AtomicBoolean(true);
        paramMap.forEach((k, v) -> {
            if (first.get()) {
                sql.append(k).append("=?");
                first.set(false);
            } else {
                sql.append(", ").append(k).append("=?");
            }
        });
        if (StringUtils.isNotEmpty(this.where)) {
            sql.append(" WHERE ").append(this.where).append(' ');
        }
        return sql.toString();
    }

    @Override
    protected ArrayList<Object> afterBuildParams(ArrayList<Object> params) {
        params.addAll(Arrays.asList(this.conditionParams));
        return params;
    }

    @Override
    public String getSqlType() {
        return "UPDATE";
    }
}
